package com.hz.authentication;

import com.hz.web.entity.RoleBean;
import com.hz.web.entity.UserBean;
import com.hz.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by kaddddd on 2018/5/8 0008.
 */
public class SpringDataUserDetailsService implements UserDetailsService {

    //登陆验证时，通过username获取用户的所有权限信息，
    //并返回User放到spring的全局缓存SecurityContextHolder中，以供授权器使用
    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException{
        try {
            //查询数据库
            UserBean user = userService.findUserByName(userName);
            if(null == user){
                throw new UsernameNotFoundException("UserName " + userName + " not found");
            }
            // SecurityUser实现UserDetails并将SUser的Email映射为username
            List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
            for (RoleBean ur : user.getRoleBeans()) {
                String name = ur.getRoleName();
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(name);
                authorities.add(grantedAuthority);
            }
            return new User(
                    user.getUsername(),
                    user.getPassword(),
                    authorities);
        }catch ( Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
